package com.example.himalaya.view_component;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya.view.activity.PlayerViewActivity;
import com.example.himalaya.R;
import com.example.himalaya.view.adapters.PlayListAdapter;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.view.callback.IPlayerViewCallback;
import com.example.himalaya.view.callback.ISobPopViewCallback;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.util.ArrayList;
import java.util.List;


// 播放列表类
public class SobPopWindow extends PopupWindow implements IPlayerViewCallback {

    @SuppressLint("StaticFieldLeak")
    private static SobPopWindow instance = null;

    // CallBack
    private List<ISobPopViewCallback> mISobPopViewCallbacks = new ArrayList<>();

    // Constant
    private final String TAG = "SobPopWindow";

    // UI object
    private final View mPopView;
    private View mCloseBtn;
    private RecyclerView mTrackList;
    private PlayListAdapter mPlayListAdapter;
    private TextView mPlayListModeTv;
    private ImageView mPlaylistMideLv;
    private View mPlayModeContainer;
    private PlayListItemClickListener mPlayListItemClickListener;
    private PlayListActionListener mPlayModeClickListener;
    private View mOrderBtnContainer;
    private ImageView mOrderIcon;
    private TextView mOrderText;

    // flag
    public boolean isReady = false;
    private final PlayerPresenter mPlayerPresenter;


    public static SobPopWindow getInstance() {

        if (instance == null) {
            synchronized (SobPopWindow.class) {
                if (instance == null) {
                    instance = new SobPopWindow();
                }
            }
        }
        return instance;
    }

    public SobPopWindow() {
        // set height width
        super(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);


        // 初始化
        this.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        this.setOutsideTouchable(true);
        // 这两步就可以关闭弹出的音乐列表

        // 加载界面
        mPopView = LayoutInflater.from(BaseApplication.getAppContext()).inflate(R.layout.pop_play_list, null);

        // 设置内容
        setContentView(mPopView);


        // 设置窗口进入和退出的动画

        this.setAnimationStyle(R.style.pop_animation);

        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();

        initView();

        initEvent();
    }

    private void initView() {
        // 先找到控件
        mCloseBtn = mPopView.findViewById(R.id.play_list_close_btn);
        mTrackList = mPopView.findViewById(R.id.play_list_tv);
        // 播放模式部分
        mPlayListModeTv = mPopView.findViewById(R.id.play_list_mode_tv);
        mPlaylistMideLv = mPopView.findViewById(R.id.play_list_play_mode_lv);
        mPlayModeContainer = mPopView.findViewById(R.id.play_list_controller_container);
        // 播放顺序
        mOrderBtnContainer = mPopView.findViewById(R.id.play_list_order_container);
        mOrderIcon = mPopView.findViewById(R.id.play_list_order_lv);
        mOrderText = mPopView.findViewById(R.id.play_list_order_tv);


        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager((BaseApplication.getAppContext()));
        mTrackList.setLayoutManager(layoutManager);
        // 设置适配器
        mPlayListAdapter = new PlayListAdapter();
        mTrackList.setAdapter(mPlayListAdapter);

        // 注册回调
        mPlayerPresenter.registerViewCallback(this);
    }

    private void initEvent() {

        // 点击关闭音乐列表的监听
        mCloseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SobPopWindow.this.dismiss();
            }
        });

        mPlayModeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 切换播放模式
                if (mPlayModeClickListener != null) {
//                    mPlayModeClickListener.onPlayModeClick();
                }

                if (mPlayerPresenter != null) {
                    // 根据当前播放模式获取下一个播放模式
                    XmPlayListControl.PlayMode playMode = PlayerViewActivity.sPlayModeRule.get(PlayerViewActivity.mCurrentMode);
                    // 通知底层改变播放模式
                    mPlayerPresenter.switchPlayMode(playMode);
                }
            }
        });

        mOrderBtnContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: 切换播放列表为顺序或者逆序
                if (mPlayModeClickListener != null) {
//                    mPlayModeClickListener.onOrderClick();
                }

                if (mPlayerPresenter != null) {
                    mPlayerPresenter.reversePlayList();
                }
            }
        });


        this.setPlayListItemClickListener(new SobPopWindow.PlayListItemClickListener() {
            @Override
            public void onItemClick(int position) {
                // 说明播放列表里面的item被点击了
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playByIndex(position);
                }
            }
        });

        this.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                for (ISobPopViewCallback sobPopCallback : mISobPopViewCallbacks) {
                    sobPopCallback.SobPopClose();
                }
            }
        });

    }

    /**
     * 给适配器设置数据
     *
     * @param data 数据
     */
    public void setListData(List<Track> data) {
        if (mPlayListAdapter != null) {
            if (data != null) {
                mPlayListAdapter.setData(data);
            }
        }
    }

    public void setCurrentPlayPosition(int position) {
        if (mPlayListAdapter != null) {
            mPlayListAdapter.setCurrentPlayPosition(position);


            mTrackList.scrollToPosition(position);

            // 播放器应该准备好了
            isReady = true;
        }
    }

    public void setPlayListItemClickListener(PlayListItemClickListener listener) {
        mPlayListAdapter.setOnItemClickListener(listener);
    }

    /**
     * 跟新播放列表的播放模式显示
     */
    public void updatePlayMode(XmPlayListControl.PlayMode playMode) {
        updatePlayModeBtnImg(playMode);
    }

    /**
     * 跟新切换顺序显示到逆序显示的UI显示方法
     *
     * @param isReverse 是否顺序
     */
    public void updateOrderIcon(boolean isReverse) {
        mOrderIcon.setImageResource(isReverse ? R.drawable.selector_play_mode_list_order : R.drawable.selector_play_mode_list_revers);
        mOrderText.setText(BaseApplication.getAppContext().getResources().getString(isReverse ? R.string.order_text : R.string.revers_text));
    }

    /**
     * 更据当前的播放模式跟新UI
     */
    private void updatePlayModeBtnImg(XmPlayListControl.PlayMode playMode) {
        int resId = R.drawable.selector_play_mode_list;
        int textId = R.string.play_mode_list_order_text;

        switch (playMode) {
            case PLAY_MODEL_LIST:
                resId = R.drawable.selector_play_mode_list;
                textId = R.string.play_mode_list_order_text;
                break;
            case PLAY_MODEL_RANDOM:
                resId = R.drawable.selector_play_mode_random;
                textId = R.string.play_mode_random_text;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resId = R.drawable.selector_play_mode_loop;
                textId = R.string.play_mode_single_loop_text;
                break;
            case PLAY_MODEL_LIST_LOOP:
                resId = R.drawable.selector_play_mode_loop_list;
                textId = R.string.play_mode_list_loop_text;
                break;
            default:
                LogUtil.d(TAG, "Some logic wrong");
                break;
        }
        mPlaylistMideLv.setImageResource(resId);
        mPlayListModeTv.setText(textId);
    }

    @Override
    public void onPlayStart() {

    }

    @Override
    public void onPlayPause() {

    }

    @Override
    public void onPlayStop() {

    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void nextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {
        setListData(list);
    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

        PlayerViewActivity.mCurrentMode = playMode;

        updatePlayMode(playMode);
    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onProgressChange(int currPos, int total) {

    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        // 设置播放列表里当前的播放位置
        setCurrentPlayPosition(playIndex);
    }

    @Override
    public void updateListOrder(boolean isReverse) {
        updateOrderIcon(isReverse);
    }

    public interface PlayListItemClickListener {
        void onItemClick(int position);
    }

    public void setPlayListActionListener(PlayListActionListener listener) {
        this.mPlayModeClickListener = listener;
    }

    public interface PlayListActionListener {
        // 播放模式被点击了
//        void onPlayModeClick();

//        // 播放逆序或者顺序切换按钮被点击了
//        void onOrderClick();
    }

    /**
     * 注册UI的回调接口
     */
    public void registerViewCallback(ISobPopViewCallback callback) {
        if (mISobPopViewCallbacks != null) {
            mISobPopViewCallbacks.add(callback);
        }
    }

    /**
     * 取消注册
     */
    public void unRegisterViewCallback(ISobPopViewCallback callback) {
        mISobPopViewCallbacks.remove(callback);
    }
}
